package server;

import server.mapper.Context;
import server.mapper.Mapper;
import server.mapper.Wrapper;

import java.io.InputStream;
import java.net.Socket;
import java.util.Map;

/**
 * @author zyy
 * @date 2020/12/29 下午8:29
 * @description
 */
public class RequestProcessor  extends Thread{
    private Socket socket;
    private Mapper mapper;

    public RequestProcessor(Socket socket, Mapper mapper) {
        this.socket = socket;
        this.mapper = mapper;
    }

    @Override
    public void run() {
        try {
            InputStream inputStream = socket.getInputStream();
            //封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());

            String[] urlArr = request.getUrl().split("/");

            //根据url匹配资源
            Servlet servlet = getServletByUrl(urlArr, mapper);

            //判断是静态资源还是动态资源（Servlet）
            //对静态资源进行处理
            if(servlet == null){
                response.outputHtml(request.getUrl());
            }else{
                // 动态资源servlet请求
                HttpServlet httpServlet = (HttpServlet) servlet;
                httpServlet.service(request,response);
            }

            socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据Url获取动态资源servlet的方法
     * @param urlArr 分割后的url数组
     * @param mapper 映射实体对象
     * @return
     */
    private Servlet getServletByUrl(String[] urlArr, Mapper mapper) {
        //获取context
        Context context = StaticResourceUtil.getContext(urlArr, mapper);

        //根据资源名匹配Wrapper中的资源并返回
        if(context == null || context.getWrappers() ==null ||context.getWrappers().isEmpty()){
            return null;
        }
        for (Wrapper wrapper : context.getWrappers()) {
            if(wrapper.getUrlPatten().equals("/"+urlArr[2])){
                return wrapper.getServlet();
            }
        }
        return null;
    }
}
